<?php

/**
 * Class 图片处理
 */
class imageChajian extends Chajian
{
	public $ext; 	//图片类型
	public $img; 	//图片对象
	public $mime; 	//图片对象
	public $path; 	//图片地址
	public $w 		= 0;
	public $h 		= 0;
	public $bool	= false;
	public $size 	= 0;
	public $whbili	= 0;//高和宽的比例
	
	
	protected function initChajian()
	{
		$this->bool	= function_exists('ImageCreate');
	}
	
	/**
		创建图片对象$rotate旋转角度
		
	*/
	public function createimg($path,$rotate=0)
	{
		if(!$this->bool)return false;
		$this->bool = false;
		if(!file_exists($path))return false;
		
		$this->ext	= $this->getext($path);
		$this->path	= $path;
		$img		= $this->createimgobj($path);
		$this->img	= $img;
		if(!$img)return false;
		//判断是否旋转
		if($rotate != 0 && $rotate<360 && $rotate>-360){
			$white	= $this->color('#ffffff',$img);
			$img	= imagerotate($img, $rotate, $white);//旋转
		}
		
		
		$this->w	= imagesx($this->img);
		$this->h	= imagesy($this->img);
		$this->size	= ceil(filesize($this->path)/1024);
		$this->whbili	= $this->w/$this->h;
		$this->bool	= true;
	}
	
	
	
	/**
		获取图片对象
	*/
	public function createimgobj($path)
	{
		$ext	= $this->getmime($path);
		$img	= false;
		switch ($ext){
			case 'image/gif':
				$img=imagecreatefromgif($path);
			break;
			case 'image/png':
				$img=imagecreatefrompng($path);
			break;
			default:
				$img=imagecreatefromjpeg($path);
			break;
		}
		return $img;
	}
	
	public function conver($opath, $npath)
	{
		if(!file_exists($opath))return;
		$img 	= $this->createimgobj($opath);
		$this->saveas($npath, $img);
	}
	
	/**
		获取图片的格式
	*/
	public function getext($img_name)
	{
		$type = strtolower(substr($img_name,strrpos($img_name,'.')+1));
		return $type;
	}
	
	public function getmime($img_name)
	{ 
		$mime = '';
		if(file_exists($img_name)){
			$fileobj	= getimagesize($img_name);
			$mime		= strtolower($fileobj['mime']);
			$this->mime = $mime;
		}
		return $mime;
	}
	
	/**
		添加文字水印
		$str	添加文字
	*/
	public function addwater($str,$color='#000000',$size=20,$align='rb')
	{
		if(!$this->bool)return;
		$font	= '../fonts/FZZHYJW.TTF';	//方正稚艺简体
		$lw 	= strlen($str)*($size/2);
		$lh		= $size*0.5;
		$color	= $this->color($color,$this->img);
		$x		= 2;
		$y		= 2;
		switch($align){
			case 'rb'://右下角
				$x		= $this->w - $lw-2;
				$y		= $this->h - $lh-2;
			break;
			case 'tr'://右上角
				$x		= $this->w - $lw-2;
			break;
			case 'lb'://左下角
				$y		= $this->h - $lh-2;
			break;
			case 'cn'://居中
				$x		= ($this->w - $lw) * 0.5;
				$y		= ($this->h - $lh) * 0.5;
			break;
		}
		imagettftext($this->img, $size,0, $x, $y, $color, $font, $str);
		$sapath	= str_replace('.'.$this->ext.'', '_water.'.$this->ext.'', $this->path);
		$sapath	= $this->path;
		$this->saveas($sapath, $this->img);//另存为
	}
	
	/**
		添加图片水印
		@params	$align 图片位置
	*/
	public function imgwater($imgpath,$align='rb')
	{
		if(!$this->bool || !file_exists($imgpath))return;
		list($lw, $lh) 	= getimagesize($imgpath);
		$logoimg		= $this->createimgobj($imgpath);
		$x				= 2;
		$y				= 2;
		switch($align){
			case 'rb'://右下角
				$x		= $this->w - $lw-2;
				$y		= $this->h - $lh-2;
			break;
			case 'tr'://右上角
				$x		= $this->w - $lw-2;
			break;
			case 'lb'://左下角
				$y		= $this->h - $lh-2;
			break;
			case 'cn'://居中
				$x		= ($this->w - $lw) * 0.5;
				$y		= ($this->h - $lh) * 0.5;
			break;
		}
		imagecopymerge($this->img, $logoimg, $x ,$y ,0 ,0 ,$lw ,$lh, 100);
		$this->saveas($this->path, $this->img);
	}
	
	/**
		创建颜色
	*/
	public function color($color,$img)
	{
		if(!empty($color)&&(strlen($color)==7)){
			$r=hexdec(substr($color,1,2));
			$g=hexdec(substr($color,3,2));
			$b=hexdec(substr($color,5));
		}else{
			$r=$g=$b='00';
		}
		return imagecolorallocate($img, $r, $g, $b);
	}
	
	/**
		注销图片
	*/
	private function destroy()
	{
		imagedestroy($this->img);
	}
	
	/**
		另存图片
	*/
	private function saveas($spath,$img)
	{
		$ext = $this->getmime($spath);
		$this->saveass($ext, $img, $spath);		
	}
	private function saveass($ext,$img, $spath)
	{
		switch($ext){
			case 'image/gif':
				imagegif($img,$spath);
			break;
			case 'image/png':
				imagepng($img,$spath);
			break;
			case 'image/bmp':
				imagewbmp($img,$spath);
			break;
			default:
				imagejpeg($img,$spath,80); 
			break;
		}		
	}
	
	/**
		图片缩略图
		@param	$w 宽
		@param	$h 高
	*/
	public function thumbnail($w,$h,$lx=0)
	{
		if(!$this->bool)return '';
		list($mw, $mh, $bili) = $this->imgwh($w,$h);
		$tmpimg = imagecreatetruecolor($w,$h);
		imagefill($tmpimg,0,0,$this->color('#ffffff',$tmpimg));
		$tx	= 0;
		$ty	= 0;
		
		//开始截的位置
		$sx	= 0;
		$sy	= 0;
		
		if($w > $mw){
			if($lx==1){//整图缩略可以看到白边
				$tx = ($w-$mw)/2;
			}else if($lx == 0){//可能去掉看不到的
				$mw = $w;
				$mh	= $mw/$this->whbili;
				$nbl= $mh/$this->h;
				$sy = ($mh-$h)/2/$nbl;	//当前缩放比例
			}
		}
		if($h > $mh){
			if($lx==1){
				$ty	= ($h-$mh)/2;
			}else if($lx == 0){
				$mh = $h;
				$mw	= $mh*$this->whbili;
				$nbl= $mw/$this->w;
				$sx = ($mw-$w)/2/$nbl;	//当前缩放比例
			}
		}
		//imagecopyresized
		imagecopyresampled($tmpimg, $this->img, $tx,$ty, $sx,$sy, $mw,$mh,$this->w,$this->h);//生成缩略图
		//$sapath	= str_replace('.'.$this->ext.'', '_thumb'.$w.'x'.$h.'.'.$this->ext.'', $this->path);
		$sapath	= str_replace('.'.$this->ext.'', '_s.'.$this->ext.'', $this->path);
		$this->saveass($this->mime ,$tmpimg, $sapath);//保存图片
		return $sapath;
	}
	
	/**
		图片显示宽高
	*/	
	public function imgwh($mw,$mh)
	{
		$w = $this->w;
		$h = $this->h;
		$bili=1;
		if($w>$mw){
			$bili=($mw/$w);
			$h=$bili*$h;
			$w=$mw;
		}
		if($h>$mh){
			$bili=($mh/$this->h);
			$w=$bili*$this->w;
			$h=$mh;
		}
		return array($w,$h,$bili);
	}

    /**
     * 生成签章图(2021-01-09 弃用)
     * @param $mark_filename 签章
     * @param $filename 签名
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2020/4/13 17:23
     */
	public function setSignatureImageDisuse($mark_filename, $filename)
    {
        $info = getimagesize($mark_filename);
        //获取图片的后缀
        $type = image_type_to_extension($info[2], false);
        //拼接图片资源句柄函数
        $func = 'imagecreatefrom' . $type;
        //创建图片资源句柄
        $images = $func($mark_filename);
//        imagesavealpha($images,true);

        //图1处理
        $info1 = getimagesize($filename);
        $type1 = image_type_to_extension($info1[2], false);
        //创建图片资源句柄
        $func1 = 'imagecreatefrom' . $type1;
        $image1 = $func1($filename);
//        imagesavealpha($image1,true);
//        $aa = $this->imgcompress($filename, $info[0], $info[1]);
        //合并背景图+图1
        $dst_x = ($info[0] - $info1[0])/2;
        $dst_y = ($info[1] - $info1[1])/1.2;
        if($dst_x <= 0) $dst_x = 0;
        if($dst_y <= 0) $dst_y = 0;

        $newImg = imagecreatetruecolor($info[0],$info[1]);
        // 关闭 alpha 渲染并设置 alpha 标志
        imagealphablending($newImg, false);
//        imagesavealpha($newImg, true);

        imagecopy($newImg, $image1, $dst_x, $dst_y, 0, 0, $info1[0], $info1[1]);
//        imagecopy($images, $image1, $dst_x, $dst_y, 0, 0, $info1[0], $info1[1]); //将 src_im 图像中坐标从 src_x，src_y 开始，宽度为 src_w，高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上

        //创建文件
        $newPath1 = $this->createDir('cache');
        if (imagepng($newImg,$newPath1)){
            imagecopy($newImg, $images, 0, 0, 0, 0, $info[0], $info[1]);
            $newPath2 = $this->createDir('cache');
            if(imagepng($newImg,$newPath2)){
                unlink($newPath1);
                list($src_w, $src_h, $type) = getimagesize($newPath2);// 获取原图像信息
                $type = image_type_to_extension($type, false);
                //创建图片资源句柄
                $func = 'imagecreatefrom' . $type;
                $src_im = $func($newPath2);
                $src_black = imagecolorallocate($src_im, 255, 255, 255);
                for ($x = 0; $x < $info[0]; $x++) {
                    for ($y = 0; $y < $info[1]; $y++) {
                        $rgb = imagecolorat($src_im, $x, $y);//获得某像素的颜色索引值
                        $r = ($rgb >> 16) & 0xFF;
                        $g = ($rgb >> 8) & 0xFF;
                        $b = $rgb & 0xFF;
                        if (($r <= 20 && $g <= 20 && $b <= 20)) {
                            imagefill($src_im, $x, $y, $src_black);//替换成白色
                        }
                    }
                }

                $target_im = imagecreatetruecolor($info[0], $info[1]);//新图
                $tag_black = imagecolorallocate($target_im, 255, 255, 255);//图像分配颜色
                imagefill($target_im, 0, 0, $tag_black);
                imagecolortransparent($target_im, $tag_black);//将某个颜色定义为透明色
                imagecopymerge($target_im, $src_im, 0, 0, 0, 0, $src_w, $src_h, 100);
                $newPath3 = $this->createDir('cache');
                if (imagepng($target_im,$newPath3)){
                    unlink($newPath2);
                    imagedestroy($target_im);
                    imagedestroy($src_im);
                    imagedestroy($newImg);
                    imagedestroy($images);
                    imagedestroy($image1);
                    return array('path' => $newPath3, 'msg' => 'SUCCESS');
                }
                imagedestroy($target_im);
                imagedestroy($src_im);
            }
        }else{
            imagedestroy($newImg);
            imagedestroy($images);
            imagedestroy($image1);
            return array('path' => '', 'msg' => 'ERROR');
        }
    }

    /**
     * Notes:将签章白色背景转换为透明（适用于扫描件白色背景红色章）
     * Author lv
     * Email 578530370@qq.com
     * Date 2020/7/27 8:40
     * @param $path 图片路径
     * @return bool|string[]
     */
    public function signaturePngs($path)
    {
        $begin_r = 220;
        $begin_g = 190;
        $begin_b = 200;
        list($src_w, $src_h, $type) = getimagesize($path);// 获取原图像信息
        $type = image_type_to_extension($type, false);
        //创建图片资源句柄
        $func = 'imagecreatefrom' . $type;
        $src_im = $func($path);

        $i = 0;
        $xAxisLeft = 0;
        $xAxisRight = 0;
        $yAxisUp = 0;
        $yAxisDown = 0;
        $src_white = imagecolorallocate($src_im, 255, 255, 255);
        for ($x = 0; $x < $src_w; $x++) {
            for ($y = 0; $y < $src_h; $y++) {
                $rgb = imagecolorat($src_im, $x, $y);//获得某像素的颜色索引值
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                if($r==255 && $g==255 && $b == 255){
                    $i ++;
                    continue;
                }

                if (($r >= $begin_r && $g >= $begin_g && $b >= $begin_b) || ($r <= 220)) {
                    imagefill($src_im, $x, $y, $src_white);//替换成白色
                }else{
//                    echo $r.','.$g.','.$b.'-'.$x.'-'.$y.'<br/>';
                    if($xAxisLeft == 0) $xAxisLeft = $x;
                    if($xAxisLeft <= $x) {
                        $xAxisLeft = $xAxisLeft;
                    }else{
                        $xAxisLeft = $x;
                    }
                    if($xAxisRight < $x) {
                        $xAxisRight = $x;
                    }
                    if($yAxisUp < $y){
                        $yAxisUp = $y;
                    }
                    if($yAxisDown == 0) $yAxisDown = $y;
                    if($yAxisDown <= $y) {
                        $yAxisDown = $yAxisDown;
                    }else{
                        $yAxisDown = $y;
                    }
                }
            }
        }
//        echo $xAxisLeft.'-'.$xAxisRight.'-'.$yAxisUp.'-'.$yAxisDown;exit;
        $width = $xAxisRight-$xAxisLeft;
        $height = $yAxisUp-$yAxisDown;

        $target_im = imagecreatetruecolor($width, $height);//新图
        $tag_white = imagecolorallocate($target_im, 255, 255, 255);//图像分配颜色
        imagefill($target_im, 0, 0, $tag_white);
        imagecolortransparent($target_im, $tag_white);//将某个颜色定义为透明色
        imagecopymerge($target_im, $src_im, 0, 0, $xAxisLeft, $yAxisDown, $width, $height, 100);

        //创建文件
        $newPath = $this->createDir();

        //创建目录，并且设置最高权限
        if (imagepng($target_im,$newPath)){
            imagedestroy($target_im);
            imagedestroy($src_im);
            unlink($path);
            return array('path' => $newPath, 'msg' => 'SUCCESS');
        }else{
            imagedestroy($target_im);
            imagedestroy($src_im);
            return array('path' => '', 'msg' => 'ERROR');
        }
    }

    /**
     * Notes:将签名背景转换为透明(字体黑)
     * Author lv
     * Email 578530370@qq.com
     * Date 2020/7/27 8:40
     * @param $path 图片路径
     * @return bool|string[]
     */
    public function namePngs($path)
    {
        $begin_r = 140;
        $begin_g = 135;
        $begin_b = 135;
        list($src_w, $src_h, $type) = getimagesize($path);// 获取原图像信息
        $type = image_type_to_extension($type, false);
        //创建图片资源句柄
        $func = 'imagecreatefrom' . $type;
        $src_im = $func($path);

        $i = 0;
        $xAxisLeft = 0;
        $xAxisRight = 0;
        $yAxisUp = 0;
        $yAxisDown = 0;
        $src_white = imagecolorallocate($src_im, 255, 255, 255);
        for ($x = 0; $x < $src_w; $x++) {
            for ($y = 0; $y < $src_h; $y++) {
                $rgb = imagecolorat($src_im, $x, $y);//获得某像素的颜色索引值
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                if($r==255 && $g==255 && $b == 255){
                    $i ++;
                    continue;
                }
                if ($r >= $begin_r || $g >= $begin_g || $b >= $begin_b) {
                    imagefill($src_im, $x, $y, $src_white);//替换成白色
                }else{
//                    echo $r.','.$g.','.$b.'<br/>';
                    if($xAxisLeft == 0) $xAxisLeft = $x;
                    if($xAxisLeft <= $x) {
                        $xAxisLeft = $xAxisLeft;
                    }else{
                        $xAxisLeft = $x;
                    }
                    if($xAxisRight < $x) {
                        $xAxisRight = $x;
                    }
                    if($yAxisUp < $y){
                        $yAxisUp = $y;
                    }
                    if($yAxisDown == 0) $yAxisDown = $y;
                    if($yAxisDown <= $y) {
                        $yAxisDown = $yAxisDown;
                    }else{
                        $yAxisDown = $y;
                    }
                }
            }
        }
//        echo $xAxisLeft.'-'.$xAxisRight.'-'.$yAxisUp.'-'.$yAxisDown;exit;
        $width = $xAxisRight-$xAxisLeft;
        $height = $yAxisUp-$yAxisDown;
        $target_im = imagecreatetruecolor($width, $height);//新图
        $tag_white = imagecolorallocate($target_im, 255, 255, 255);//图像分配颜色
        imagefill($target_im, 0, 0, $tag_white);
        imagecolortransparent($target_im, $tag_white);//将某个颜色定义为透明色
        imagecopymerge($target_im, $src_im, 0, 0, $xAxisLeft, $yAxisDown, $width, $height, 100);

        //创建文件
        $newPath = $this->createDir();

        //创建目录，并且设置最高权限
        if (imagepng($target_im,$newPath)){
            imagedestroy($target_im);
            imagedestroy($src_im);
            unlink($path);
            return array('path' => $newPath, 'msg' => 'SUCCESS');
        }else{
            imagedestroy($target_im);
            imagedestroy($src_im);
            return array('path' => '', 'msg' => 'ERROR');
        }
    }

    /**
     * Notes:压缩图片
     * Author lv
     * Email 578530370@qq.com
     * Date 2020/7/28 9:36
     * @param $path 图片路径
     * @param $width 指定宽
     * @return string[]
     */
    public function imgcompress($path, $width = 150)
    {
        $info = getimagesize($path);
        //获取图像类型的文件后缀
        $type = image_type_to_extension($info[2], false);
        //计算压缩比
        $percent = $width/$info[0];
        //创建图片资源句柄
        $func1 = 'imagecreatefrom' . $type;
        $image = $func1($path);
        imagesavealpha($image,true);

        $image_p = imagecreatetruecolor($info[0]*$percent, $info[1]*$percent);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $info[0]*$percent, $info[1]*$percent, $info[0], $info[1]);

        //创建文件
        $newPath = $this->createDir();

        if (imagepng($image_p, $newPath)){
            imagedestroy($image_p);
            unlink($path);
            return array('path' => $newPath, 'msg' => 'SUCCESS');
        }else{
            imagedestroy($image_p);
            return array('path' => '', 'msg' => 'ERROR');
        }
    }

    /**
     * 使用imageMagick处理透明图片
     * @param $path 原图路径
     * @param $type publicSeal 公章 privateSeal 手章  sign 签名
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2021/1/9 10:23
     */
    public function imageMagick($path, $type) {
        $ouput = $this->createDir();
        if ($type == 'publicSeal') {
            $bgcolor="white"; //背景颜色。可使用十六进制色码和rgb(1,1,1)
            $fuzz="6500"; //容差
            $size = "200x200";
            if(PATH_SEPARATOR==';'){
//                $str = exec("magick $path -resize $size -fuzz $fuzz -transparent $bgcolor $ouput >> E:\webRoot\oa\log_file.log 2>&1 &");
                $str = exec("magick $path -resize $size -fuzz $fuzz -transparent $bgcolor $ouput");
                if(empty($str)) $str = exec("magick $ouput -alpha Set -channel A +level 0,70% +channel $ouput");
            }else{
                $str = exec("convert -resize $size $path -fuzz $fuzz -transparent $bgcolor $ouput"); //转透明
                if(empty($str)) $str = exec("convert $ouput -matte -channel A +level 0,70% +channel $ouput");
            }
            //die;
        } elseif($type == 'privateSeal') {
            $bgcolor="white"; //背景颜色。可使用十六进制色码和rgb(1,1,1)
            $fuzz="6500"; //容差
            $size = "120x120";
            if(PATH_SEPARATOR==';'){
                $str = exec("magick $path -resize $size -fuzz $fuzz -transparent $bgcolor $ouput");
            } else {
                $str = exec("convert -resize $size $path -fuzz $fuzz -transparent $bgcolor $ouput");
            }
        } else {
            $bgcolor="white"; //背景颜色。可使用十六进制色码和rgb(1,1,1)
            $fuzz="6500"; //容差
            $size = "130x50";
            if(PATH_SEPARATOR==';'){
                $str = exec("magick $path -resize $size -fuzz $fuzz -transparent $bgcolor $ouput");
            } else {
                exec("./textcleaner -g -e stretch -f 25 -o 5 -s 1 $path $path");
                $str = exec("convert -resize $size $path -fuzz $fuzz -transparent $bgcolor $ouput");
            }
        }
        if (empty($str)) {
            return array('path' => $ouput, 'msg' => 'SUCCESS', 'code' => 1);
        } else {
            return array('path' => '', 'msg' => 'ERROR', 'code' => -1);
        }
    }
    
    public function setPhpImgOpacity($path){
    }
    /**
     * 使用imageMagick生成有透明度的签章图
     * @param $mark_filename 签章
     * @param $filename 签名
     */
    public function setOpacity($path,$opcity=0.75){
        $ouput = $this->createDir();
        $color = new ImagickPixel("#ffffff"); 
        $alpha = '0.0';//0到1之间 背景透明度
        $fuzz  = '0.2';//0到1之间 和上面的颜色相似度
        $imagick = new Imagick($path);
        //宽高
        $imagick->matteFloodfillImage(0.85, 0, 'red', 0, 0);
        $clut = new Imagick(); 
  
        // Imagick object choosen green color from color lookup table 
        $clut->newImage(1, 1, new ImagickPixel('red')); 
          
        // No channel is applied hence default channel is used 
        $imagick->clutImage($clut); 

        //宽高
        $imagick->matteFloodfillImage(0.85, 0, 'red', 0, 0);
        //保存图片
        $imagick->writeImage($ouput);
        $imagick->clear();
        $imagick->destroy();
        return $ouput;
    }

    /**
     * 使用imageMagick生成签章图
     * @param $mark_filename 签章
     * @param $filename 签名
     * @Auther: lv
     * @Email: 578530370@qq.com
     * @Date: 2021/1/9 10:23
     */
    public function setSignatureImage($mark_filename, $filename)
    {
        if(!empty($mark_filename) && !empty($filename)){
            $newPath = $this->createDir('cache');
            if(PATH_SEPARATOR==';'){
                $str = exec("magick $mark_filename -compose over $filename -geometry 130x50+25+100 -composite $newPath");
            } else {
                $str = exec("convert $mark_filename -compose over $filename -geometry 130x50+25+100 -composite $newPath");
            }
            if(empty($str)){
                return array('path' => $newPath, 'msg' => 'SUCCESS');
            }
        }
        return array('path' => '', 'msg' => 'ERROR');
    }

    public function createDir($type='')
    {
        if($type == 'cache') {
            $dirName = './upload/cache/'.date('Y-m', time());
        }else{
            $dirName = './upload/signature/'.date('Y-m', time());
        }
        $path = $dirName.'/'.uniqid().'.png';//存储的路径

        //判断目录是否存在
        if (is_dir($dirName) == false){
            //创建目录，并且设置最高权限
            mkdir($dirName, 0777, true);
        }
        return $path;
    }
}